/*
 * @Description: 角色导航组件
 * @Author: Rfan
 * @Date: 2022-03-31 14:00:56
 * @LastEditTime: 2023-02-27 09:28:30
 */

import { useEffect } from 'react';
import { Menu, Tag } from 'antd';
import classNames from 'classnames/bind';
import type { SelectEventHandler } from 'rc-menu/lib/interface';
import { observer } from 'mobx-react-lite';
import { useRoleContext } from '../contexts/RoleContext';
import { appState } from '@/store/mobx';

import styles from '../styles/roleSidebar.module.scss';

const cx = classNames.bind(styles);

/**
 * @description: 部门导航组件
 * @return {*}
 */
const RoleSidebar = (): any => {
  const { selectRoleId, roleList, setSelectRoleId, getRoleList } = useRoleContext();

  // 获取角色列表
  // 加载时获取单位列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    getRoleList(appState.unitId);
  }, [appState.unitId]);

  /**
   * @description: Menu组件设置为受控组件，选中节点时设置选中的key并将选中的内容返回出去
   * @param {React.Key[]} selectedKeys
   */
  const onSelect: SelectEventHandler = ({ selectedKeys }) => {
    if (selectedKeys.length > 0) {
      setSelectRoleId(selectedKeys[0]);
    }
  };

  return (
    <div className={cx('container')}>
      <h6 className={cx('department-header')}>角色列表</h6>
      <div className="fond-navs">
        <Menu
          items={roleList.map((item: any) => ({
            label: (
              <>
                {item.roleName}
                {item.roleType === 1 && (
                  <Tag color="#108ee9" className={cx('role-tag')}>
                    全宗
                  </Tag>
                )}
              </>
            ),
            key: item.id
          }))}
          mode="vertical"
          selectedKeys={[selectRoleId]}
          onSelect={onSelect}
        />
      </div>
    </div>
  );
};

export default observer(RoleSidebar);
